import { components, router } from '@/router'
import { RouteRecordRaw } from 'vue-router'
/**
 * @description 创建层级关系
 * @param tree 树
 * @param pathList 每一项的id组成的数组
 * @returns 创建层级关系后的树
 */
export const buildHierarchyTree = (tree: any[], pathList = []): any => {
  if (!Array.isArray(tree)) {
    console.warn("tree must be an array");
    return [];
  }
  if (!tree || tree.length === 0) return [];
  for (const [key, node] of tree.entries()) {
    node.id = key;
    node.parentId = pathList.length ? pathList[pathList.length - 1] : null;
    node.pathList = [...pathList, node.id];
    const hasChildren = node.children && node.children.length > 0;
    if (hasChildren) {
      buildHierarchyTree(node.children, node.pathList);
    }
  }
  return tree;
};

/** 处理动态路由（后端返回的路由） */
export const handleAsyncRoutes = (routeList: any) => {
  // 处理后的数据
  const processedData: any = [];
  // 遍历后端返回的路由数据
  if (routeList && routeList.length !== 0) {
    routeList.forEach((item: any) => {
      //权限未启用
      if (item.isDisabled) return
      // 创建祖先级路由对象
      let parentRoute: any = {
        path: "/",
        name: item.id,
        meta: { title: item.title, sort: item.sort, icon: item.icon, auth: [] },
        component: () => import("@/design/scaffold/index.vue"), // 异步导入组件
        children: []
      };
      //祖先级为菜单路由
      if (item.component && components[item.component]) {
        // 获取子路由对应的组件配置
        let comRoute = components[item.component];
        comRoute.meta.title = item.title
        comRoute.meta.sort = item.sort
        /**处理标签和元素 */
        comRoute.meta.auth = []
        if (item.children && item.children.length !== 0) {
          item.children.forEach((tag: any) => {
            if (tag.mark && !tag.isDisabled) {
              comRoute.meta.auth.push(tag.mark)
              if (tag.component && components[tag.component]) {
                // 获取标签元素子路由对应的组件配置
                let tagRoute = components[tag.component];
                tagRoute.meta.title = tag.title
                tagRoute.meta.sort = tag.sort
                parentRoute.children.push(tagRoute) //将标签元素路由添加到祖先路由的children中
              }
            }
          })
        }
        parentRoute.children.push(comRoute) // 将子路由添加到父路由的children中
      } else {
        //祖先级为目录路由
        if (item.children.length !== 0 && item.type == 0) {
          item.children.forEach((com: any) => {
            if (com.component && !com.isDisabled && components[com.component]) {
              // 获取子路由对应的组件配置
              let comRoute = components[com.component];
              comRoute.meta.title = com.title
              comRoute.meta.sort = com.sort
              /**处理孙子路由标签和元素 */
              comRoute.meta.auth = []
              if (com.children && com.children.length !== 0) {
                com.children.forEach((tag: any) => {
                  if (tag.mark && !tag.isDisabled) {
                    comRoute.meta.auth.push(tag.mark)
                    if (tag.component && components[tag.component]) {
                      // 获取标签元素子路由对应的组件配置
                      let tagRoute = components[tag.component];
                      tagRoute.meta.title = tag.title
                      tagRoute.meta.sort = tag.sort
                      parentRoute.children.push(tagRoute) //将标签元素路由添加到祖先路由的children中
                    }
                  }
                })
              }
              parentRoute.children.push(comRoute) // 将子路由添加到父路由的children中
            }
          })
          if (parentRoute.children.length == 0) {
            parentRoute.children.push({
              path: '/blank',
              name: 'blank',
              component: () => import('@/design/error/blank.vue'),
            })
          }
        } else {
          parentRoute.children.push({
            path: '/blank',
            name: 'blank',
            component: () => import('@/design/error/blank.vue'),
          })
        }
      }

      processedData.push(parentRoute); // 将处理好的父路由添加到处理后的数据中
    })
  }
  processedData.forEach((route: RouteRecordRaw) => {
    router.addRoute(route);
  });
  console.log('处理的路由', processedData) // 输出处理后的路由数据
  return processedData; // 返回处理后的路由数据
}

/**
 * @description 构造树型结构数据
 * @param data 数据源
 * @param id id字段 默认id
 * @param title title名称字段 默认title
 * @param parentId 父节点字段，默认parentId
 * @param parentTitle 父节点名称字段，默认parentTilte
 * @param children 子节点字段，默认children
 * @returns 追加字段后的树
 */
export const handleTree = (
  data: any[],
  id?: string,
  title?: string,
  parentId?: string,
  parentTitle?: string,
  children?: string
): any => {
  if (!Array.isArray(data)) {
    console.warn("data must be an array");
    return [];
  }
  const config = {
    id: id || "id",
    title: title || "title",
    parentId: parentId || "parentId",
    parentTitle: parentTitle || "parentTitle",
    childrenList: children || "children"
  };
  // 深拷贝传入的 data 解决改变原数据
  const copiedData = JSON.parse(JSON.stringify(data));

  const childrenListMap: any = {};
  const nodeIds: any = {};
  const tree: any = [];

  for (const d of copiedData) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of copiedData) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t, null);
  }

  function adaptToChildrenList(o: Record<string, any>, parentTitle: string | null) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c, o[config.title]);
      }
    }
    if (parentTitle !== null) {
      o[config.parentTitle] = parentTitle;
    }
  }
  return tree;
};

/**menu匹配小图标 */
export const menuTreeIcon = (title: string) => {
  switch (title) {
    default:
      return title;
  }
}
